/*
 * Generic Arduino-Scala project
 *
 * Idea - connect arduino to PC and control arduino io from Scala
 *
 * First "real" usage will probably be a Scala-fed hot-wire CNC-cutter
 * for creating 3D foam "sculptures" for airfoils etc.
 *
 * Author: Christoffer Vaaben Ladefoged - christoffer@degofedal.dk
 * 
 */
#define BUFFER_SIZE 256

char inputBuffer[BUFFER_SIZE];
int bufferIndex = 0;

#define MS1 5
#define MS2 6
#define STEP 2
#define DIR 3
#define SLEEP 4

void setup() {
     // initialize comm-port
     Serial.begin(9600);

     // initialize digital pins
     // pinMode(0, INPUT); - don't touch - RX
     // pinMode(1, OUTPUT); - don't touch - TX
     pinMode(2, OUTPUT);
     pinMode(3, OUTPUT);
     pinMode(4, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(7, OUTPUT);
     pinMode(8, OUTPUT);
     pinMode(9, OUTPUT);
     pinMode(10, OUTPUT);
     pinMode(11, OUTPUT);
     pinMode(12, OUTPUT);
     pinMode(13, OUTPUT);
     
     // set full speed
     digitalWrite(MS1, HIGH);
     digitalWrite(MS2, HIGH);
     
     digitalWrite(DIR, LOW);
     
     digitalWrite(SLEEP, HIGH);
     int i=0;
     while(i < 2000) {
       digitalWrite(STEP,LOW);
       digitalWrite(STEP,HIGH);
       i = i + 1;  
       delayMicroseconds(1500);
     }
     digitalWrite(SLEEP, LOW);
     
     
     Serial.println("msg|Setup done");
}

void loop() {
     // loop executed by the microcontroller

     // handle input
     if(Serial.available() > 0) {
         while(Serial.available()) {
	     char in = Serial.read();
	     if(in == ';') {
	         // input assumed complete
		 handleMessage();		 
	     } else {
	         inputBuffer[bufferIndex] = Serial.read();
	     	 bufferIndex++;
	     }
	 }
	 
     }

     // execute current work

     // send status/output

}

void handleMessage() {
    // simple echo
    for(int i = 0; i < bufferIndex; i++) {
        Serial.print(inputBuffer[i], BYTE);
    }
    Serial.println();
}
